<?php
namespace App\Controllers\Classc;

use App\Configs\Web\Common;
use App\Libs\Base\Constant;
use App\Libs\Helper\CommonHelper;
use App\Libs\Views\Json;
use App\Models\ClassModel\ClassModel;
use App\Models\Task\Task;
use App\Models\User\User;
/*
 *  返回类别：
 *          如果get参数含有：
 *          1：
 *              task_id：分页返回任务是此任务的班级；
 *              page：1
 *              size：10，
 *          2：
 *              class_type:班级类型：分页返回指定的班级类型：1：挑战班，2：悬赏班，3：体验班;
 *              page:1
 *              size:10
 *          3:
 *              uid:返回某人创建的所有班级，uid即用户的id，每个班级都返回有uid，
 *              page：1
 *              size：10
 *          4:
 *              class_name：此项为搜索：搜索班级名称中包含指定关键词的班级;中文需要进行urlencode
 *              page:1
 *              size:10
 *          5：
 *              分页返回所有的班级；
 *              page：1
 *              size：10，
 *          6:
                 获取推荐到班级首页的班级
                recommend:将班级类型传入此字段即可获得相应班级类型推荐到班级首页的班级列表
 *  排序方式：
 *          排序方式由字段：order接收，order可以有多重组合方式，所以order的值是一个数组转换成的json字符串;
 *              'person_asc'             按照报名人数升序
 *              'pserson_desc'           按照报名人数降序
 *              'task_period_asc'        按照任务周期升序
 *              'task_period_desc'       按照任务周期降序
 *              'class_punch_card_asc'   按照每周打卡频率升序
 *              'class_punch_card_desc'  按照打卡频率降序
 *
 *  */
class GetClassList extends \App\Libs\Base\BaseAction
{
    private $order_method = [
        'person_asc'                => 'class_person asc',
        'pserson_desc'              => 'class_person desc',
        'task_period_asc'           => 'class_task_period asc',
        'task_period_desc'          => 'class_task_period desc',
        'class_punch_card_asc'      => 'class_punch_card asc',
        'class_punch_card_desc'     => 'class_punch_card desc',

    ];

    private $queryField = [
        'task_id',
        'class_type',
        'uid',
        'class_name'
    ];
    public function execute()
    {
        $page = $this->request->getQuery('page','int',1);
        $size = $this->request->getQuery('size','int',10);
        $offset = ($page-1)*$size;
        //搜索方式
        if($this->request->hasQuery('task_id')){
            $task_id = $this->request->getQuery('task_id');
            if(empty($task_id)){
                return Json::view(1,'传入正确 的任务id',[]);
            }
            $conditions = [
                'conditions' => 'class_task_sel='.$task_id,
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }elseif($this->request->hasQuery('class_type')){
            $class_type = $this->request->getQuery('class_type'); //1:挑战班，2：悬赏班，3：体验班;
            if(!in_array($class_type,['1','2','3'])){
                return Json::view(1,'班级类型错误',[]);
            }
            $conditions = [
                'conditions' => 'class_type='.$class_type,
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }elseif ($this->request->hasQuery('uid')){
            $uid = $this->request->getQuery('uid');
            $conditions = [
                'conditions'=>'uid='.$uid,
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }elseif($this->request->hasQuery('class_name')){
            $key = $this->request->getQuery('class_name');
            if(empty($key)){
                return Json::view(1,'请输入正确的班级名称进行搜索',[]);
            }
            $conditions = [
                'conditions'=>'class_name like "%'.$key.'%"',
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }elseif($this->request->hasQuery('recommend')){
            $recom = $this->request->getQuery('recommend');
            if(empty($recom) || !in_array($recom,['2','3'])){
                return Json::view(1,'推荐的类型错误',[]);
            }
            $conditions = [
                'conditions'=>'class_type=?1 and class_recommend=2',
                'bind' => [1=>$recom],
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }else{
            $conditions = [
                'conditions' => '1=1',
                'columns' => 'id,uid,class_name,class_icon,class_task_sel,class_person,class_task_period,class_task_credit,class_type,class_status,class_jiesuan,class_recommend',
            ];
        }
        //排序条件；
        if(!$this->request->hasQuery('order')){
            $conditions['order'] = 'class_status asc,class_jiesuan asc';
        }else{
            $order = json_decode($this->request->getQuery('order'));
            $newOrderMethod = array_intersect($this->order_method,$order);
            if(empty($newOrderMethod)){
                $conditions['order'] = 'class_status asc,class_jiesuan asc';
            }elseif (count($newOrderMethod) == '1'){
                $orderKey = array_keys($newOrderMethod);
                $conditions['order'] = $newOrderMethod[$orderKey[0]];
            }elseif (count($newOrderMethod) >= 2){
                $conditions['order'] = implode(',',$newOrderMethod);
            }
        }
        $sum = ClassModel::count($conditions['conditions']);
        if(empty($sum)){
            return Json::view(0,'没有更多数据了',['class'=> [],'sum'=>$sum]);
        }else{
            $conditions = array_merge($conditions,[
                    'offset' => $offset,    
                    'limit' => $size
            ]);
            $matchClass = ClassModel::findAll($conditions)->toArray();
            $createUserArray = [];
            foreach ($matchClass as $key => $val){
                $createUserArray[] = $val['uid'];
                $taskArray[] = $val['class_task_sel'];
            }
            $matchUsers = User::findAll([
                'id in ({ddd:array})',
                'bind' => ['ddd' => $createUserArray],
                'columns' => 'id as uid,username,avatar as user_avatar',
            ])->toArray();
            $matchTask = Task::findAll([
                'id in ({ddd:array})',
                'bind' => ['ddd' => $taskArray]
            ])->toArray();
            if(!empty($matchUsers)){
                $transMatchUsers = CommonHelper::setColToKey($matchUsers,'uid');
            }
            if(!empty($matchTask)){
                $transMatchTask = CommonHelper::setColToKey($matchTask,'id');
            }
            foreach ($matchClass as $key => $val){
                if($val['uid'] == '0'){
                    $matchClass[$key]['creater_name']  = Constant::APP_NAME;
                    $matchClass[$key]['creater_avatar'] = Constant::APP_AVATAR;
                }elseif(isset($transMatchUsers[$val['uid']])){
                    $matchClass[$key]['creater_name'] = $transMatchUsers[$val['uid']]['username'];
                    $matchClass[$key]['creater_avatar'] = $transMatchUsers[$val['uid']]['user_avatar'];
                }
                if(isset($transMatchTask[$val['class_task_sel']])){
                    $matchClass[$key]['class_task_sel_name'] = $transMatchTask[$val['class_task_sel']]['task_title'];
                }else{
                    $matchClass[$key]['class_task_sel_name'] = '未知任务';
                }
            }
            return Json::view(0,'ok',['class'=> $matchClass,'sum'=>$sum]);
        }
    }
}
